<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <script>
    // JSON 对象和普通对象的区别  JSON数据 key值要加双引号
    var car1 = {//对象
      name: "本田",
      color: "红色"
    }
    var car2 = {//对象
      "name": "本田",
      "color": "红色"
    }
    // JSON 转换
    // 1) JSON转字符串 JSON.stringify()
    var carstr = JSON.stringify(car2)
    console.log(carstr)
    // 2) 字符串转Json  JSON.parse()
    var carjson = JSON.parse(carstr)
    console.log(carjson)

    //栈内存 存储 基本数据类型 和引用数据类型的地址
    //堆内存 存储的引用数据类型的数据
    var obj = {
      name: "张",
      age: 2,
      arr: [1, 2, 3],
      sex: {
        xiao: "男",
        gao: "女",
        gong: {
          am: "nan",
          pm: "nv"
        }
      }
    }
    var myobj = obj;
    myobj.age = 5;
    console.log(obj.age)
    // 深拷贝和浅拷贝
    // 浅拷贝 只拷贝对象的第一层内容
    var benchi = {
    }
    for (var x in obj) {
      benchi[x] = obj[x];
    }
    console.log(benchi)
    benchi.age = 18;
    console.log(obj.age)
    benchi.sex.xiao = "人妖"
    console.log(obj.sex.xiao)
    // 深拷贝
    // 1 JSON.parse(JSON.stringify(对象))
    var mylist = JSON.parse(JSON.stringify(obj))
    mylist.sex.gao = "女人"
    console.log(obj.sex.gao)
    //2深拷贝函数
    function deepClone(obj) {
      var myobj = {}
      for (var x in obj) {
        myobj[x] = typeof obj[x] === "Object" ? deepClone(obj[x]) : obj[x]
      }
      return myobj
    }

    // 深拷贝
    function deepClone(obj) {
      var type = Object.prototype.toString.call(obj);  //通过原型对象获取对象类型
      var newObj;
      if (type === '[object Array]') {
        //数组
        newObj = [];
        if (obj.length > 0) {
          for (var x = 0; x < obj.length; x++) {
            newObj.push(deepClone(obj[x]));
          }
        }
      } else if (type === '[object Object]') {
        //对象
        newObj = {};
        for (var x in obj) {
          newObj[x] = deepClone(obj[x]);
        }
      } else {
        //基本类型和方法可以直接赋值
        newObj = obj;
      }
      return newObj;
    }
  </script>
</body>

</html>